use std::fmt;
use actix_web::{HttpResponse, ResponseError};
use serde::Serialize;
use crate::extends::core::errors::response_code_enums::ResponseCodeEnum;

#[derive(Debug, Serialize)]
pub struct GlobalBusinessError {
    pub(crate) code: u16,
    msg: String,
    error: String,
}

impl GlobalBusinessError {
    pub fn new(response_code: ResponseCodeEnum, error: String) -> Self {
        let code = response_code.to_response();
        GlobalBusinessError {
            code: code.code,
            msg: code.msg,
            error,
        }
    }
}

impl fmt::Display for GlobalBusinessError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "GlobalBusinessError: code={}, msg={}, error={}", self.code, self.msg, self.error)
    }
}

impl ResponseError for GlobalBusinessError {
    fn error_response(&self) -> HttpResponse {
        HttpResponse::build(actix_web::http::StatusCode::from_u16(self.code).unwrap())
            .json(self)
    }
}
